import { useEffect, useState } from 'react';
import PropTypes from 'prop-types'; // 引入 PropTypes
import { Col, Row, Card, message, Pagination, Modal, Form, Input, InputNumber, Button, Breadcrumb, Upload } from 'antd';
import { EditOutlined, CloseOutlined, UploadOutlined } from '@ant-design/icons';
import { productManagement } from '../../../../apis/auth';
import './content.less';

const ProductManagement1 = ({ isAdding, setIsAdding }) => {
    const [products, setProducts] = useState([]);
    // const [addProduct, setAddProduct] = useState(null);
    const [current, setCurrent] = useState(1);
    const [total, setTotal] = useState(0);
    const [editingProduct, setEditingProduct] = useState(null);
    const [isModalVisible, setIsModalVisible] = useState(false);

    const pageSize = 8;

    useEffect(() => {
        getProducts(current, pageSize);
    }, [current, pageSize]);
  //获取默认展示商品
    const getProducts = async (page, pageSize) => {
        try {
            const response = await productManagement.getAllProducts(page, pageSize);
            if (response.data.code === 200) {
                setProducts(response.data.data.list);
                setTotal(response.data.data.total);
            } else {
                message.error(response.data.message);
            }
        } catch (error) {
            message.error('获取商品信息失败，请稍后再试');
        }
    };
//编辑商品
   
    const handleEdit = (product) => {
        setEditingProduct(product);
        setIsModalVisible(true);
    };
 //分页器控制更新商品
    const onPageChange = (page, pageSize) => {
        setCurrent(page);
        getProducts(page, pageSize);
    };
  //删除商品
    const handleDelete = async (productId) => {
        try {
            await productManagement.deleteProduct(productId);
            message.success('商品删除成功');
            getProducts(current, pageSize);
        } catch (error) {
            message.error('商品删除失败，请稍后再试');
        }
    };
  //取消编辑，关闭模态框和编辑函数
    const handleCancel = () => {
        setIsModalVisible(false);
        setEditingProduct(null);
    };

  //编辑商品成功相关函数
    const handleOk = async (values) => {
        try {
            await productManagement.updateProduct({ ...editingProduct, ...values });
            message.success('商品信息修改成功');
            setIsModalVisible(false);
            setEditingProduct(null);
            getProducts(current, pageSize);
        } catch (error) {
            message.error('商品信息修改失败，请稍后再试');
        }
    };
 
    //添加商品
    const handleAddProduct = async (values) => {
        const { categoryId, commodityName, cost, currentPrice, dangerInventory, inventory, sellingUnit ,file } = values;
        console.log('handleAddProduct values:', values); // 调试日志  不加下面的话发现虽然params正常传递但是，file显示传递是数组，因此需要从file数组中提取originFileObj 作为文件对象传递给 adManagement.addAd 函数。

        const fileObject = file[0].originFileObj; // 获取文件对象
        try {
            await productManagement.addProduct(categoryId, commodityName, cost, currentPrice, dangerInventory, inventory, sellingUnit, fileObject);
            message.success('商品添加成功');
            setIsAdding(false);
            getProducts();
        } catch (error) {
            message.error('商品添加失败');
        }
    };
//一级页面商品展示
if(!isAdding){

    return (
        <>
            <Row gutter={[16, 16]}>
                {products.map((product) => (
                    <Col className="product-col" key={product.id} xs={24} sm={12} md={6}>
                        <Card
                            className="product-card"
                            actions={[
                                <EditOutlined key="edit" onClick={() => handleEdit(product)} />,
                                <CloseOutlined key="delete" onClick={() => handleDelete(product.id)} />,
                            ]}
                            cover={<img alt={product.commodityName} src={product.file} className="product-image" />}
                        >
                            <h1 label='商品名称' className="product-title">{product.commodityName}</h1>
                            <p>价格: {product.currentPrice}</p>
                            <p>库存: {product.inventory}</p>
                            <p>状态: {product.inventoryStatus ? '有库存' : '缺货'}</p>
                            <p>分类: {product.categoryId}</p>
                        </Card>
                    </Col>
                ))}
            </Row>
            <Pagination
                current={current}
                total={total}
                pageSize={pageSize}
                onChange={onPageChange}
                showSizeChanger
                onShowSizeChange={onPageChange}
            />
            <Modal
                title="编辑商品"
                visible={isModalVisible}
                onCancel={handleCancel}
                footer={null}
            >
                <Form
                    initialValues={editingProduct}
                    onFinish={handleOk}
                >
                    <Form.Item name="commodityName" label="商品名称">
                        <Input />
                    </Form.Item>
                    <Form.Item name="currentPrice" label="价格">
                        <InputNumber />
                    </Form.Item>
                    <Form.Item name="inventory" label="库存">
                        <InputNumber />
                    </Form.Item>
                    <Form.Item name="inventoryStatus" label="库存状态">
                        <InputNumber />
                    </Form.Item>
                    <Button type="primary" htmlType="submit">
                        保存
                    </Button>
                </Form>
            </Modal>
        </>
    );
}
    
    
    else {
        return (
            <div>
                <Breadcrumb
                    items={[
                        {
                            title: '商品信息管理',
                        },
                        {
                            title: '新增商品',
                        }
                    ]}
                />
                <Form layout="vertical" onFinish={handleAddProduct} style={{ marginTop: 16 }}>
                    <Form.Item
                        name="commodityName "
                        label="商品名称"
                        rules={[{ required: true, message: '请输入商品名称' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="categoryId "
                        label="商品分类"
                        rules={[{ required: true, message: '请输入商品分类' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="cost"
                        label="商品成本"
                        rules={[{ required: true, message: '请输入商品成本' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="currentPrice"
                        label="商品现价"
                        rules={[{ required: true, message: '请输入商品现价' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="inventory"
                        label="商品库存"
                        rules={[{ required: true, message: '请输入商品库存' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="dangerInventory"
                        label="商品警戒库存"
                        rules={[{ required: true, message: '请输入商品警戒库存' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="sellingUnit"
                        label="售卖单位"
                        rules={[{ required: true, message: '请输入售卖单位' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="file"
                        label="上传广告图片"
                        valuePropName="fileList"
                        getValueFromEvent={(e) => {
                            if (Array.isArray(e)) {
                                return e;
                            }
                            return e && e.fileList;
                        }}
                        rules={[{ required: true, message: '请上传广告图片' }]}
                    >
                        <Upload beforeUpload={() => false}>
                            <Button icon={<UploadOutlined />}>选择图片</Button>
                        </Upload>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">添加</Button>
                        <Button onClick={() => setIsAdding(false)} style={{ marginLeft: 8 }}>取消</Button>
                    </Form.Item>
                </Form>
            </div>
        );
    }
};

// 为 AdManagement 组件添加 prop 类型验证
ProductManagement1.propTypes = {
    isAdding: PropTypes.bool,
    setIsAdding: PropTypes.func,
};



export default ProductManagement1;
